<script lang="ts" setup name="VabChangePassword">
import { FormInstance, FormRules } from 'element-plus'
import { md5 } from 'js-md5'
import { User } from '~/src/api/interface/user'
import { changePasswordAPI } from '~/src/api/user'
import { useUserStore } from '~/src/store/modules/user'
import { toLoginRoute } from '~/src/utils/routes'
import { Emits, Props } from '../VabSettingUser/interface'
const route = useRoute()
const router = useRouter()
const props = defineProps<Props>()
const emits = defineEmits<Emits>()
const visible = useVModel(props, 'modelValue', emits)
const { logout } = useUserStore()

const form = reactive<User.ChangePriceForm>({
  userId: null,
  oldPsw: '',
  newPsw: '',
  samePsw: '',
})

// 密码校验
const validatePass = (rule: any, value: string, callback: any) => {
  const finalCheckPwd = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/

  // 校验密码
  const checkPwd: boolean = finalCheckPwd.test(form.newPsw)

  if (!checkPwd) {
    callback(new Error('密码必须不少于8位, 包含大小写、字母、字符至少三种'))
  } else {
    callback()
    // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
  }
}
const rules: FormRules = {
  oldPsw: [{ required: true, message: '请输入当前密码' }],
  newPsw: [
    { required: true, message: '请输入新密码' },
    { validator: validatePass, trigger: ['blur'] },
  ],
  samePsw: [
    { required: true, message: '请输入确认密码' },
    {
      validator: (rules: any, value: string, callback: Function) => {
        if (value !== form.newPsw) return callback(new Error('新密码于确认密码不一致，请重新输入'))
        callback()
      },
      trigger: ['blur'],
    },
  ],
}
const formRef = ref<FormInstance>()

const onConfirm = async (type: string) => {
  if (type === 'submit') {
    await formRef.value?.validate()
    await changePasswordAPI({ oldPsw: md5(form.oldPsw), newPsw: md5(form.newPsw), userId: null })
    ElMessage.success('修改密码成功,请重新登录')
    logout()
    await router.push(toLoginRoute(route.fullPath)) // 跳转后登录后还能跳转回来
  }
  visible.value = false
}
</script>

<template>
  <div>
    <vab-dialog v-model:modelValue="visible" title="修改密码" width="500px">
      <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
        <el-form-item label="当前密码" prop="oldPsw">
          <el-input v-model.trim="form.oldPsw" placeholder="" show-password type="password" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPsw">
          <el-input v-model.trim="form.newPsw" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="samePsw">
          <el-input v-model.trim="form.samePsw" placeholder="" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onConfirm('submit')">保存</el-button>
        <el-button @click="onConfirm('cancel')">取消</el-button>
      </template>
    </vab-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
